package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.utils.overlay.SmoothMoveMarker;
import com.bigkoo.pickerview.TimePickerView;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.PersonRouteE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.StationMapShowBiz;
import com.infore.airsupervise.biz.impl.StationMapShowBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;


/**
 * 人员历史踪迹界面
 * Created by xiaotao on 2017/7/28.
 */

public class PeresonRouteActivity extends BaseTitleBarActivity implements AMap.OnMapLoadedListener,
        AMap.OnMarkerClickListener, AMap.InfoWindowAdapter {
    private static final int TYPE_START = 1;
    private static final int TYPE_END = 2;
    private static final int TYPE_SITE = 3;

    @BindView(R.id.map_view)
    TextureMapView mapView;
    @BindView(R.id.tv_time)
    EditText etTime;
    @BindView(R.id.iv_after)
    ImageView ivAfter;


    private TimePickerView timePickerView= null;
    private SweetAlertDialog dialog = null;

    private Polyline mPolyline;
    private SmoothMoveMarker smoothMarker = null;
    private View infoWindow = null;

    private AMap aMap = null;
    private String userId = null;
    private String time = null;
    private List<PersonRouteE> route_list = null;
    private List<LatLng> latlntList = null;

    private StationMapShowBiz mapShowBiz = null;

    private boolean isEnd = true ; //

    private boolean[] showType = new boolean[]{true, true, true, false, false, false};



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_route);
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);
        Intent it = getIntent();
        if (null != it) {
            userId = it.getStringExtra(Constants.INTENT_STR_KEY);
        }
        initView();
    }

    private void initView() {
        //titleBar
        title.setText("历史踪迹");
        rightMenu.setVisibility(View.INVISIBLE);
        initMapView();
        route_list = new ArrayList<>();
        //时间显示
        etTime.setText(DateUtil.updateTime(
                DateUtil.getCurrentDateStr(false), StatusConst.STATISTIC_DAY, false));
        etTime.addTextChangedListener(textChangeListener);
    }

    /**
     * 初始化地图
     */
    private void initMapView() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);
        uiSettings.setScaleControlsEnabled(false);
        uiSettings.setMyLocationButtonEnabled(false);
        aMap.setOnMapLoadedListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);
    }

    private void initMarker(int type, PersonRouteE routeE, LatLng latLng, int index) {
        MarkerOptions options = new MarkerOptions();
        options.infoWindowEnable(false);
        options.position(latLng);
        options.anchor(0.5f, 0.5f);
        if (type == TYPE_START) {
            options.icon(BitmapDescriptorFactory.fromResource(R.drawable.start));
        } else if (type == TYPE_END) {
            options.icon(BitmapDescriptorFactory.fromResource(R.drawable.end));
        } else if (type == TYPE_SITE) {
            View view = LayoutInflater.from(ctx).inflate(R.layout.layout_marker_site, null);
            TextView tv_site = (TextView) view.findViewById(R.id.tv_site);
            tv_site.setText(index + "");
            options.icon(BitmapDescriptorFactory.fromView(view));
            options.infoWindowEnable(true);
            options.title("");
        }

        aMap.addMarker(options).setObject(routeE);
    }

    /**
     * 添加轨迹线
     */
    private void addPolyline() {
        PolylineOptions mPolyOptions = new PolylineOptions();
        mPolyOptions.addAll(latlntList)
                .width(15f).color(R.color.colorPrimary);
        mPolyline = aMap.addPolyline(mPolyOptions);
        startMoveMarker();
    }

    private void startMoveMarker() {
        if (mPolyline == null || latlntList == null || latlntList.size() <= 0) {
            ToastUtil.showShort(ctx, "无相关轨迹");
            return;
        }
        // 实例 SmoothMoveMarker 对象
        if (smoothMarker != null) {
            smoothMarker.destroy();
        }
        smoothMarker = new SmoothMoveMarker(aMap);
        smoothMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.drawable.walkman));
        smoothMarker.setVisible(true);
        // 设置轨迹点
        smoothMarker.setPoints(latlntList);
        smoothMarker.getMarker().hideInfoWindow();
        smoothMarker.getMarker().setInfoWindowEnable(false);
        // 设置平滑移动的总时间  单位  秒
        smoothMarker.setTotalDuration(30);

        // 开始移动
        smoothMarker.startSmoothMove();
    }

    /**
     * 获取历史轨迹网络请求
     */
    private void getPersonRoute() {
        if (mapShowBiz == null) {
            mapShowBiz = new StationMapShowBizImpl();
        }
        dialog = new SweetAlertDialog(ctx, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        if (aMap != null) {
            aMap.clear();
        }
        mapShowBiz.sendPersonRouteRequest(userId, etTime.getText().toString(), responseListener);
    }

    /**
     * 获取轨迹点集合
     */
    private LatLngBounds.Builder getRouteMarker(List<PersonRouteE> result) {
        if (latlntList == null) {
            latlntList = new ArrayList<>();
        }
        latlntList.clear();
        LatLngBounds.Builder builder = new LatLngBounds.Builder(); //地图可见区域
        for (int i = 0; i < result.size(); i++) {
            LatLng latlng = new LatLng(result.get(i).getLat(), result.get(i).getLnt());
            latlntList.add(latlng);
            builder.include(latlng);
            if (i == 0) { //起点
                initMarker(TYPE_START, result.get(i), latlng, i);
            }
            if (i == result.size() - 1 && i != 0) { //终点
                initMarker(TYPE_END, result.get(i), latlng, i);
            }
//            if (i == 2) { // 对应了站点位置
//                initMarker(TYPE_SITE, result.get(i), latlng, i);
//            }
            if(!TextUtils.isEmpty(result.get(i).getSpecial())){
                initMarker(TYPE_SITE, result.get(i), latlng, i);
            }
        }

        return builder;
    }


    /**
     * 初始化时间选择
     */
    private void initDatePicker(){
        Calendar endSelectedDate = Calendar.getInstance();
        endSelectedDate.add(Calendar.DAY_OF_MONTH,-1);
        timePickerView = new TimePickerView.Builder(ctx,timeSelectListener )
                .setTitleText("")
                .setLabel("年", "月", "日", "点", "分", "秒")
                .setType(showType)
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(18)
                .setRangDate(null , endSelectedDate)
                .setDate(endSelectedDate)
                .setDecorView(null)
                .build();
    }

    /**
     * 地图初始化地图成功后的回调
     */
    @Override
    public void onMapLoaded() {
        getPersonRoute();
    }

    /**
     * 标记点击事件
     *
     * @param marker
     * @return
     */
    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        } else {
            aMap.animateCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
            marker.showInfoWindow();
        }
        return true;
    }


    private TextWatcher textChangeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (DateUtil.compareDate(s.toString(), DateUtil.updateTime(
                    DateUtil.getCurrentDateStr(false), StatusConst.STATISTIC_DAY, false),DateUtil.FORMAT_DATE) <= 0) {
                isEnd = true ;
            }else {
                isEnd = false ;

            }
        }
    };

    /**
     * 网络请求回调
     */
    private OnServerResponseListener<List<PersonRouteE>> responseListener = new OnServerResponseListener<List<PersonRouteE>>() {
        @Override
        public void onSucceed(List<PersonRouteE> result, String desc) {
            dialog.dismiss();
            aMap.clear();
            if(result == null){
                return ;
            }
            LatLngBounds.Builder builder = getRouteMarker(result);
            if(latlntList.size() > 1) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
            }else if (latlntList.size() == 1){
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlntList.get(0),15f));
            }
            addPolyline();

        }

        @Override
        public void onFailed(int errorCode, String title, String desc) {
            //dialog 错误 异常提示
            dialog.setTitleText(title)
                    .setContentText(desc)
                    .setConfirmText(MsgConst.I_SEE)
                    .changeAlertType(SweetAlertDialog.WARNING_TYPE);
        }
    };


    /**
     * 基本控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_before, R.id.iv_after ,R.id.tv_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_before:
                etTime.setText(DateUtil.updateTime(etTime.getText().toString(),StatusConst.STATISTIC_DAY, false));
                getPersonRoute();
                break;
            case R.id.iv_after:
                if(!isEnd) {
                    etTime.setText(DateUtil.updateTime(etTime.getText().toString(), StatusConst.STATISTIC_DAY, true));
                    getPersonRoute();
                }else {
                    ToastUtil.showShort(ctx,"不能超过当前日期");
                }
                break;
            case R.id.tv_time :
                if(timePickerView == null) {
                    initDatePicker();
                }
                timePickerView.show();
                break;
        }
    }

    /**
     * 时间选择监听
     */
    TimePickerView.OnTimeSelectListener timeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            etTime.setText(DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE));
            getPersonRoute();
        }
    };
    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        if(infoWindow == null){
            infoWindow = LayoutInflater.from(ctx).inflate(R.layout.layout_window_route,null);
        }
        render(marker,infoWindow);
        return infoWindow;
    }

    private void render(Marker marker ,View view ){
        PersonRouteE routeE = (PersonRouteE) marker.getObject();
        if(routeE==null){
            return ;
        }
        TextView name = (TextView) view.findViewById(R.id.station_name);
        TextView updateTime = (TextView) view.findViewById(R.id.update_time);
        TextView airLevel = (TextView) view.findViewById(R.id.air_level);
        TextView address = (TextView) view.findViewById(R.id.station_address);
        updateTime.setText(routeE.getTime());
        address.setText(routeE.getAddress());
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (smoothMarker != null) {
            smoothMarker.stopMove();
            smoothMarker.destroy();
        }
        if (mPolyline != null) {
            mPolyline.remove();
        }
        if (aMap != null) {
            aMap.clear();
        }
        mapShowBiz = null;
        dialog = null;
        latlntList = null;
        route_list = null;
    }


}
